package com.xieyong.leetcode;

public class Leetcode1432 {
    public static void main(String[] args) {
        Leetcode1432 leetcode1432 = new Leetcode1432();
        int num = 555;
        int i = leetcode1432.maxDiff(num);
        System.out.println(i);
    }


    public int maxDiff(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        char flag = 'a';
        for (int i = 0; i < chars.length; i++) {
            if (flag == 'a') {
                if (chars[i] != '9') {
                    flag = chars[i];
                    chars[i] = '9';
                }
            } else {
                if (chars[i] == flag) {
                    chars[i] = '9';
                }
            }
        }
        int max = Integer.parseInt(String.valueOf(chars));

        char[] minchars = String.valueOf(num).toCharArray();
        char firstchar = minchars[0];
        char minflag = 'b';
        boolean secondflag = false;
        if (firstchar != '1') {
            minflag = firstchar;
            secondflag = true;
        }
        for (int i = 0; i < minchars.length; i++) {
            if (secondflag){
                if (minchars[i] == minflag) {
                    minchars[i] = '1';
                }
            } else {
                if (minflag == 'b') {
                    if (minchars[i] != '0' && minchars[i] != '1') {
                        minflag = minchars[i];
                        minchars[i] = '0';
                    }
                } else {
                    if (minchars[i] == minflag) {
                        minchars[i] = '0';
                    }
                }
            }
        }
        int min = Integer.parseInt(String.valueOf(minchars));
        return max - min;
    }
}
